package com.tan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tan.domain.User;
import com.tan.domain.response.Result;
import com.tan.domain.response.StatusCode;
import com.tan.mapper.UserMapper;
import com.tan.service.UserService;
import com.tan.util.TokenUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Resource
    UserMapper userMapper;

    @Override
    public Result login( Map<String, User> para) {
        User user = para.get("user");
        if (user == null ) {
            return new Result(true, StatusCode.ERROR, "登录失败");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("USERNAME", user.getUsername());
        User u = userMapper.selectOne(queryWrapper);
        if (u != null && u.getPassword().equals(user.getPassword())) {
            String token = TokenUtil.sign(u);
            u.setLastLoginTime(new Date());
            u.setLoginCity(user.getLoginCity());
            u.setLoginLat(user.getLoginLat());
            u.setLoginLng(user.getLoginLng());
            u.setLoginProvince(user.getLoginProvince());
            userMapper.updateById(u);
            Map<String, Object> info = new HashMap<>();
            User newUser = userMapper.selectById(u.getId());
            info.put("user", newUser);
            info.put("token", token);
            return new Result(true, StatusCode.OK, "登录成功",info);
        } else {
            return new Result(true, StatusCode.ERROR, "登录失败");
        }
    }

    @Override
    public Result register(Map<String, User> param) {
        User user = param.get("user");
        if (user == null) {
            return new Result(true, StatusCode.ERROR, "注册失败", null);
        }
        userMapper.insert(user);
        String token = TokenUtil.sign(user);
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("token", token);
        return new Result(true, StatusCode.OK, "注册成功", map);
    }
}




